export class SQL {
    constructor(params) {
        const { tableName } = params
        this.tableName = tableName
    }

    /**
     * 返回创建数据表的 sql 语句
     * @param {string} name
     * @param {string[]} columns
     */
    static createTable(tableName, columns) {
        return `CREATE TABLE IF NOT EXISTS ${tableName} (${columns.join(',')})`
    }

    /**
     * 生成条件
     * @param {WhereParams} params
     */
    where(params) {
        if (!params || !params.conditions) return ''
        const {
            conditions = [],
            operator = 'and',
        } = params
        if (typeof conditions === 'string') return conditions
        if (conditions.length === 1) return conditions[0]
        return conditions.join(` ${operator} `)
    }

    /**
     * 返回插入数据的 sql 语句
     * @param {string[]} columns
     */
    insert(insertObject) {
        const entries = Object.entries(insertObject)
        const columns = entries.map(entry => entry[0])
        const params = entries.map(entry => entry[1])        
        const sql = `INSERT INTO ${this.tableName} (${columns.join(',')}) VALUES (${Array(columns.length).fill('?').join(',')})`
        return {
            sql,
            params
        }
    }

    select(columns, whereParams) {
        const columnsSyntax = Array.isArray(columns) && columns.length > 0 ? columns.join(',') : '*'
        const whereSyntax = this.where(whereParams)
        return `SELECT ${columnsSyntax} FROM ${this.tableName} ${whereSyntax ? `WHERE ${whereSyntax}`: ''}`
    }

    update(updateObject, whereParams) {
        const setSyntax = Object.entries(updateObject).map(([key, value]) => `${key} = ${value}`).join(',')
        const whereSyntax = this.where(whereParams)
        return `UPDATE FROM ${this.tableName} SET ${setSyntax} WHERE ${whereSyntax}`
    }

    delete(whereParams) {
        const whereSyntax = this.where(whereParams)
        return `DELETE FROM ${this.tableName} WHERE ${whereSyntax}`
    }
}
